package com.gitee.lougnib.hellowebim.module.chatroom.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.filter.OncePerRequestFilter;

import com.gitee.lougnib.hellowebim.common.mybatis.service.ChatRoomUserService;
import com.gitee.lougnib.hellowebim.module.chatroom.constant.ChatRoomConsts;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@WebFilter(urlPatterns = ChatRoomConsts.PATH_REST_FILTER, asyncSupported = true)
public class ChatRoomUserFilter extends OncePerRequestFilter {

    @Autowired
    private ChatRoomUserService userService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String visitorId = request.getHeader(ChatRoomConsts.HEADER_KEY_VISITOR_ID);
        log.debug("{} , visitor id = {}, isAsyncSupported = {}, isAsyncStarted = {}", request.getRequestURI(), visitorId, request.isAsyncSupported(), request.isAsyncStarted());

        if (StringUtils.isBlank(visitorId)) {
            response.sendError(HttpStatus.BAD_REQUEST.value());
            log.debug("无效请求，visitor id 是空的", visitorId);
            return;
        }

        userService.saveVisitor(visitorId, request.getHeader("User-Agent"));
        Integer accessLevel = userService.getAccessLevel(visitorId);
        if (accessLevel == null || accessLevel.intValue() == 0) {
            response.sendError(HttpStatus.UNAUTHORIZED.value());
            log.debug("visitor id = {} 无权限访问", visitorId);
            return;
        }

        filterChain.doFilter(request, response);
    }

}
